package com.mango.amazon.util;

import com.alibaba.fastjson.JSONObject;
import com.amazon.AmazonSpiSite;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentials;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentialsProvider;
import com.amazon.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import com.amazon.spapi.definitionsProductTypes_2020_09_01.ApiException;
import com.amazon.spapi.definitionsProductTypes_2020_09_01.api.DefinitionsApi;
import com.amazon.spapi.definitionsProductTypes_2020_09_01.model.ProductTypeDefinition;
import com.fasterxml.jackson.databind.JsonNode;

import com.github.fge.jackson.JsonLoader;

import com.github.fge.jackson.JsonNodeReader;

import com.github.fge.jsonschema.core.report.LogLevel;

import com.github.fge.jsonschema.core.report.ProcessingMessage;

import com.github.fge.jsonschema.core.report.ProcessingReport;

import com.github.fge.jsonschema.main.JsonSchemaFactory;

import com.mango.amazon.APIfactory;
import org.springframework.util.ResourceUtils;

import java.io.ByteArrayOutputStream;
import java.io.FileReader;

import java.io.IOException;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class JsonSchemaUtil {


    /**
     * @param jsonStr 验证json字符串
     */

    public static JsonNode strToJsonNode(String jsonStr) {

        JsonNode jsonNode = null;

        try {

            jsonNode = JsonLoader.fromString(jsonStr);

        } catch (IOException e) {

            e.printStackTrace();

        }

        return jsonNode;

    }

    /**
     * @param jsonFilePath jsonSchema文件路径
     */

    public static JsonNode schemaToJsonNode(String jsonFilePath) {

        JsonNode jsonSchemaNode = null;

        try {

            jsonSchemaNode = new JsonNodeReader().fromReader(new FileReader(ResourceUtils.getFile(jsonFilePath)));

        } catch (IOException e) {

            e.printStackTrace();

        }

        return jsonSchemaNode;

    }

    /**
     * @param jsonNode   json数据node
     * @param schemaNode jsonSchema约束node
     */

    public static boolean getProcessingReport(JsonNode jsonNode, JsonNode schemaNode) {

//fge验证json数据是否符合json schema约束规则

        ProcessingReport report = JsonSchemaFactory.byDefault().getValidator().validateUnchecked(schemaNode, jsonNode);

        if (report.isSuccess()) {

// 校验成功

            return true;

        } else {

            Iterator it = report.iterator();

            StringBuilder ms = new StringBuilder();

            ms.append("json格式错误: ");

            while (it.hasNext()) {

                ProcessingMessage pm = (ProcessingMessage) it.next();

                if (!LogLevel.WARNING.equals(pm.getLogLevel())) {

                    ms.append(pm);

                }

            }

            System.err.println(ms);

            return false;

        }

    }

    public static JsonNode getJsonSchemaNode() throws ApiException {
        List<String> marketplaceIds = new ArrayList<>();
        marketplaceIds.add("ATVPDKIKX0DER");

        ProductTypeDefinition call = APIfactory.definitionsApi.getDefinitionsProductType("BOOKEND", marketplaceIds, null, null, null, null, "zh_CN");

        String jsonSchema = readFileByUrl(call.getSchema().getLink().getResource());


        JsonNode jsonSchemaNode = strToJsonNode(jsonSchema);

        return jsonSchemaNode;
    }


    /*工具类*/
    public static String readFileByUrl(String urlStr) {
        String res = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            res = readInputStream(inputStream);
        } catch (Exception e) {
            System.out.println("通过url地址获取文本内容失败 Exception：" + e);
        }
        return res;
    }

    /**
     * 从输入流中获取字符串
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static String readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        // System.out.println(new String(bos.toByteArray(), "utf-8"));
        return new String(bos.toByteArray(), "utf-8");
    }


}